#include "camera.h"

matrix44 camera_t::getViewMatrix() const
{
	return TranslateMatrix44(0.0, 0.0, -m_fDistance) * LookAtMatrix44(eye, up, dir) * RotateRadMatrix44('y', -m_fPhi) * RotateRadMatrix44('x', m_fTheta);
}

matrix44 camera_t::getProjectionMatrix() const
{
	return PerspectiveMatrix44(m_fViewAngle, m_fW/m_fH, m_fNear, m_fFar);
}

vector3 camera_t::getPosition() const
{
	matrix44 mView = getViewMatrix();
	mView.invert();
	return vector3(mView * vector4(0.0f, 0.0f, 0.0f, 1.0f));
}

void camera_t::setProjection( float viewAngle, float w, float h, float near, float far )
{
	m_fViewAngle = viewAngle;
	m_fW = w;
	m_fH = h;
	m_fFar = far;
	m_fNear = near;
}

void camera_t::mouseProc( int uMsg, int x, int y )
{
	static bool bWasLeftButtonDown = false, bWasRightButtonDown = false;
	static int  oldx = 0, oldy = 0;

	if( bWasLeftButtonDown )
	{
		float a = DegToRad(180.0f)/300.0f;
		m_fPhi += (float)(x-oldx)*a;
		m_fTheta += (float)(oldy-y)*a;
	}
	else
	if( bWasRightButtonDown )
	{
		float a = 0.1f;
		m_fDistance -= (float)(oldy-y)*a;
		if (m_fDistance < 0.01f)
			m_fDistance = 0.01f;
		if (m_fDistance > 100.0f)
			m_fDistance = 100.0f;
	}

	oldx = x;
	oldy = y;
	if( uMsg == LBUTTONDOWN )
		bWasLeftButtonDown = true;
	if( uMsg == LBUTTONUP )
		bWasLeftButtonDown = false;
	if( uMsg == RBUTTONDOWN )
		bWasRightButtonDown = true;
	if( uMsg == RBUTTONUP )
		bWasRightButtonDown = false;
}

void camera_t::setViewMatrix(vector3 _eye, vector3 _up, vector3 _direction)
{
	eye = _eye;
	dir = _direction;
	up = _up;
}